/**
 * 
 */
package com.spider.silence.pool;

import java.util.LinkedList;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.TianYaDownLoader;
import com.spider.silence.utils.PropertiesUtil;

/**
 * @title TianYaDownLoaderPool.java
 * @author liyuanguo
 * @time 2017年1月9日 上午9:38:26
 * @description
 * @version V1.0
 */
public class TianYaDownLoaderPool {
	private static TianYaDownLoaderPool  instance= new TianYaDownLoaderPool();;
	 protected  LinkedList<TianYaDownLoader> pool = Lists.newLinkedList();
	    private   TianYaDownLoaderPool(){
	       for(int i=0;i<Integer.valueOf(PropertiesUtil.getVal("TianYa.DownLoader.Pool.initNum"));i++){
	    	   TianYaDownLoader downLoader =new TianYaDownLoader();
	            downLoader.init();
	            pool.add(downLoader);
	       }
	    };
	    public  static TianYaDownLoaderPool getInstance(){
	        return  instance;
	    }
	    public  void releaseDownLoader(TianYaDownLoader downloader) {
	        if (downloader != null) {
	            synchronized (pool) {
	                pool.addLast(downloader);
	                pool.notifyAll();
	            }
	        }
	    }
	    public  TianYaDownLoader fetchDownLoader(long mills) throws InterruptedException {
	        synchronized (pool){
	            if(mills<=0){
	                while (pool.isEmpty()){
	                    pool.wait();
	                }
	                return pool.removeFirst();
	            }else {
	                long future= System.currentTimeMillis()+mills;
	                long remianing=mills;
	                while (pool.isEmpty() && remianing >0){
	                    pool.wait(remianing);
	                    remianing=future-System.currentTimeMillis();
	                }
	                TianYaDownLoader downLoader =null;
	                if(!pool.isEmpty()){
	                    downLoader=pool.removeFirst();
	                }
	                return downLoader;
	            }
	        }
	    }

	    /**
	     * 清空池
	     */
	    public void empty(){
	        pool=Lists.newLinkedList();
	    }
}
